/*******************************************************************************
 * Copyright (c) 2012, G. Weirich and Elexis
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    G. Weirich - initial implementation
 *******************************************************************************/

package ch.elexis.easy.core;

import java.io.File;
import java.io.FileInputStream;

import org.eclipse.core.runtime.ILog;
import org.eclipse.core.runtime.Platform;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.application.WorkbenchAdvisor;
import org.osgi.framework.Bundle;

import ch.elexis.core.IConfiguration;
import ch.elexis.core.Session;
import ch.elexis.core.data.IPersistentObjectManager;
import ch.elexis.core.util.PlatformHelper;
import ch.elexis.persistence.sql.PersistentObjectManager;
import ch.rgw.io.InMemorySettings;

/**
 * This class controls all aspects of the application's execution and is contributed through the
 * plugin.xml.
 */
public class Hub implements IApplication {
	public static final String ID = "ch.elexis.easy";
	public static Hub theInstance;
	Session session;
	
	public Object start(IApplicationContext context) throws Exception{
		theInstance = this;
		if (session == null) {
			InMemorySettings cfg = new InMemorySettings();
			cfg.set(PersistentObjectManager.CFG_BASEPATH, System.getProperty("user.home")
				+ File.separator + "testdb");
			cfg.set(PersistentObjectManager.CFG_DEFAULT_DB_PATH, System.getProperty("user.home")
				+ File.separator + "testdb/database");
			cfg.set(PersistentObjectManager.CFG_TYPE, "H2");
			File rscdir =
				new File(PlatformHelper.getBasePath(PersistentObjectManager.PluginID), "rsc");
			FileInputStream fis = new FileInputStream(new File(rscdir, "createDB.sql"));
			IConfiguration config = Configuration.getInstance();
			IPersistentObjectManager pom =
				new ch.elexis.persistence.sql.PersistentObjectManager(cfg, fis);
			session = new Session(pom, config);
		}
		Display display = PlatformUI.createDisplay();
		WorkbenchAdvisor advisor = new ApplicationWorkbenchAdvisor();
		return PlatformUI.createAndRunWorkbench(display, advisor);
	}
	
	public ILog getLog(){
		Bundle bundle = Platform.getBundle(ID);
		if (bundle != null) {
			return Platform.getLog(bundle);
		}
		return null;
	}
	
	public void stop(){
		if (session != null) {
			session.terminate();
		}
	}
}
